<?php

/*@LICENSE@*/

require_once 'Clouseau/Genealogy/Tree/Exporter.php';

/**
 * An exporter to GML for a genealogy tree.
 * http://www.infosun.fim.uni-passau.de/Graphlet/GML/gml-tr.html
 * @author Thomas Quémard <thomas.quemard@gmail.com>
 **/
class Clouseau_Genealogy_Tree_Exporter_Gml extends Clouseau_Genealogy_Tree_Exporter
{
	protected $_sTab = '   ';
	protected $_aAssoc = array();
	protected $_iEdges = 0;
	protected $_iNodes = 0;
	protected $_sNodes = '';
	protected $_sEdges = '';

	protected function _exportNode(Clouseau_Genealogy_Node &$oNode)
	{
		$this->_sNodes .= $this->_sTab . 'node [' . "\n";
		$this->_sNodes .= $this->_tab(2) . 'id ' . $this->_iNodes . "\n";
		$this->_sNodes .= $this->_tab(2) . 'label "' . $oNode->getName() . "\"\n";
		$this->_sNodes .= $this->_sTab . ']' . "\n";

		foreach ($oNode as $oChild)
		{
			if (!is_null($oChild))
			{
				++ $this->_iNodes;
				++ $this->_iEdges;
				
				$this->_aAssoc[$oChild->getName()] = $this->_iNodes;

				$this->_sEdges .= $this->_sTab . 'edge [' . "\n";
				$this->_sEdges .= $this->_tab(2) . 'id ' . $this->_iEdges . "\n";
				$this->_sEdges .= $this->_tab(2) . 'source ' . $this->_aAssoc[$oNode->getName()] . "\n";
				$this->_sEdges .= $this->_tab(2) . 'target ' . $this->_aAssoc[$oChild->getName()] . "\n";
				$this->_sEdges .= $this->_sTab . ']' . "\n";
				
				$this->_exportNode($oChild);
			}
		}
		return $s;
	}

	protected function _tab($i=1)
	{
		return str_repeat($this->_sTab, $i);
	}

	public function export(Clouseau_Genealogy &$oTree)
	{
		$this->_aAssoc[$oTree->getName()] = 0;
		$this->_exportNode($oTree);
		$s = "graph [\n";
		$s .= $this->_sTab . 'Creator "Clouseau"' . "\n";
		$s .= $this->_sNodes;
		$s .= $this->_sEdges;
		$s .= "]";
		return $s;
	}
}
